package com.keyancompany.zhongbaopingtai.fragment;

import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSONObject;
import com.keyancompany.zhongbaopingtai.Constants;
import com.keyancompany.zhongbaopingtai.R;
import com.keyancompany.zhongbaopingtai.activity.WeeklyDetailActivity;
import com.keyancompany.zhongbaopingtai.adapter.WeeklyAdapter;
import com.keyancompany.zhongbaopingtai.api.TeamAPI;
import com.keyancompany.zhongbaopingtai.api.UserAPI;
import com.keyancompany.zhongbaopingtai.listener.IAsyncHttpResponseHandler;
import com.keyancompany.zhongbaopingtai.model.BaseModel;
import com.keyancompany.zhongbaopingtai.model.EventBusEntity;
import com.keyancompany.zhongbaopingtai.model.LoadWeekly;
import com.keyancompany.zhongbaopingtai.model.TeamUser;
import com.keyancompany.zhongbaopingtai.model.Weekly;
import com.keyancompany.zhongbaopingtai.utils.IntentUtils;
import com.keyancompany.zhongbaopingtai.utils.T;
import com.keyancompany.zhongbaopingtai.weight.IListView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemClick;


/**
 * A fragment representing a list of Items.
 * <p/>
 * interface.
 */
public class WeeklyFragment extends BaseFragment implements IAsyncHttpResponseHandler, SwipeRefreshLayout.OnRefreshListener {

    private static final String TYPE = "type";

    @Bind(R.id.list_view)
    IListView listView;

    @Bind(R.id.find_swipe_layout)
    SwipeRefreshLayout swipeLayout;

    @Bind(R.id.empty_view)
    LinearLayout mEmptyView;

    private WeeklyAdapter mTaskAdapter;
    int total = 1, currentPage = 1;

    private String teamCode;
    private int type = 1;//个人 1   团队 0
    List<Weekly> allWeeklies;
    List<Weekly> myWeeklies;

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the
     * fragment (e.g. upon screen orientation changes).
     */
    public WeeklyFragment() {
    }

    /**
     * @param teamCode
     * @param type
     * @return
     */
    public static WeeklyFragment newInstance(String teamCode, int type) {
        WeeklyFragment fragment = new WeeklyFragment();
        Bundle args = new Bundle();
        args.putString(Constants.TEAM_CODE, teamCode);
        args.putInt(TYPE, type);
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public int getContentViewId() {
        return R.layout.fragment_weekly;
    }

    @Override
    public void setUpViews() {
        teamCode = getArguments().getString(Constants.TEAM_CODE);
        type = getArguments().getInt(TYPE);
        allWeeklies = new ArrayList<>();

        initSwipeLayout(swipeLayout);
        swipeLayout.setOnRefreshListener(this);
        mTaskAdapter = new WeeklyAdapter(getActivity());
        listView.setAdapter(mTaskAdapter);

        listView.setStateListener(new IListView.SwipeLayoutState() {
            @Override
            public boolean isRefresh() {
                return swipeLayout.isRefreshing();
            }

            @Override
            public boolean isLastPage() {
                return total == currentPage;
            }

            @Override
            public void requestNextPage() {
                requestTask(++currentPage, false);
            }
        });


        if (isNetvaiable()) {
            swipeLayout.post(new Thread(new Runnable() {

                @Override
                public void run() {
                    swipeLayout.setRefreshing(true);
                    onRefresh();
                }
            }));
        }
    }

    private void requestTask(int currentPage, boolean isNeedLoad) {
        if (isNetvaiable()) {//pegenombers:分页页码
            TeamAPI.loadWeekly(teamCode, type + "", this, isNeedLoad ? getLoading(R.string.watting_hint) : null);
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(EventBusEntity event) {
//        //（1）将事件发布者发布的数据作为文本修改内容
//        msgFragment.setText(event.data);
        //（2）将事件发布者发布的数据作为方法执行的区分
        switch (event.getType()) {
            case EventBusEntity.Type.REFRENCE_WEEKLY:
                swipeLayout.post(new Thread(new Runnable() {

                    @Override
                    public void run() {
                        swipeLayout.setRefreshing(true);
                        onRefresh();
                    }
                }));
                break;
        }
    }
    @OnItemClick(R.id.list_view)
    public void listItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position < mTaskAdapter.getCount()) {
            Bundle bundle = new Bundle();
            bundle.putString(Constants.TEAM_CODE, teamCode);
            bundle.putString(Constants.WEEKLY_ID, mTaskAdapter.getItem(position).getId());
            IntentUtils.startActivity(getActivity(), WeeklyDetailActivity.class, bundle);
        }
    }

    @OnClick(R.id.empty_hint)
    public void reqeustAgain(View v) {
//        TeamAPI.teamTask(teamCode, type, currentPage, this, getLoading(-1));
        currentPage = 1;
        requestTask(currentPage, true);
    }


    @Override
    public void start(int type) {

    }

    @Override
    public void success(int type, String json) {
        if (getActivity() == null)
            return;
        swipeLayout.setRefreshing(false);
        BaseModel base = JSONObject.parseObject(json, BaseModel.class);
        if (base.isSuccess()) {
            LoadWeekly loadWeekly = JSONObject.parseObject(base.data, LoadWeekly.class);
            if (base.result.equals(Constants.SUCESS)) {
                currentPage = loadWeekly.getPager().getPageNumber();
                if (currentPage == 1) {
                    mTaskAdapter.clear();
                }
                listView.loadMoreFinish();
                if (total == currentPage) {
                    listView.removeFooterView();
                }
                total = loadWeekly.getPager().getPageSize();

                if (loadWeekly.getPager().getList().size() > 0) {
                    allWeeklies = loadWeekly.getPager().getList();
                    myWeeklies = new ArrayList<>();
                    String currenUserId = UserAPI.getUserId();
                    for (Weekly weekly : allWeeklies) {
                        if (currenUserId.equals(weekly.getUserCode())) {
                            myWeeklies.add(weekly);
                        }
                    }

                    if (type == 1) {
                        if (!myWeeklies.isEmpty()) {
                            swipeLayout.setVisibility(View.VISIBLE);
                            mEmptyView.setVisibility(View.GONE);
                            mTaskAdapter.addAllAfter(myWeeklies);
                        } else {
                            swipeLayout.setVisibility(View.GONE);
                            mEmptyView.setVisibility(View.VISIBLE);
                        }
                    } else {
                        if (!allWeeklies.isEmpty()) {
                            swipeLayout.setVisibility(View.VISIBLE);
                            mEmptyView.setVisibility(View.GONE);
                            mTaskAdapter.addAllAfter(allWeeklies);
                        } else {
                            swipeLayout.setVisibility(View.GONE);
                            mEmptyView.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    T.showShort(getActivity(), "当前暂无周报内容！");
                    return;
                }
            }
        } else {
            T.showShort(getActivity(), base.msg);
        }
    }

    @Override
    public void failed(String error) {
        swipeLayout.setRefreshing(false);
        T.showShort(getActivity(), error);
    }

    @Override
    public void finish(int type) {

    }


    @Override
    public void onRefresh() {
        currentPage = 1;
        requestTask(currentPage, false);

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }
}
